# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
import re
import redis

from django.shortcuts import render, redirect
from django.http import JsonResponse


from .models import HotelOrder
from room.models import Room, RoomStatus, RoomType
from users.models import Customer

conn = redis.Redis(host='118.89.225.98',port=6379)

# Create your views here.
def chick_in_hotel(request):
    res = {}
    msg = ''
    if request.method == 'POST':
        name = request.POST.get('name')
        id_card = request.POST.get('id_card')
        people_num = request.POST.get('people')
        mobile = request.POST.get('mobile')
        s_time = request.POST.get('startDate')
        e_time = request.POST.get('endDate')
        gender = request.POST.get('gender')
        room_type = request.POST.get('room_type')
        room_num = request.POST.get('room_num')
        save_customer(name, mobile, id_card, gender)
        money = request.POST.get('money')
        money = re.findall('\d+', money)[0]
        if not room_num:
            room = Room.objects.filter(type=int(room_type), status=1)[:1]
            room_num = room[0].num
        Room.objects.filter(num=room_num).update(status=5)
        order = HotelOrder.objects.create(
            name = name,
            id_card = id_card,
            people_num = people_num,
            mobile = mobile,
            s_time = datetime.datetime.now(),
            e_time = datetime.datetime.strptime(e_time+' 12', '%Y-%m-%d %H'),
            type = 1,
            gender = gender,
            room_type =room_type,
            room_num = room_num,
            money=money,
        )
        order.save()
        msg = name + '的信息办理成功！房间号：' + room_num
    search_room(res)
    room_id = request.GET.get('room')
    if room_id:
        r = Room.objects.get(num=room_id)
        res['room_type'] = r.type
        res['room_num'] = room_id
    res['active'] = 'enter'
    res['display'] = 1
    res['msg'] = msg
    return render(request, 'enter_hotel.html', res)

def save_customer(name, mobile, id_card, gender):
    try:
        Customer.objects.get(id_card=id_card)
    except Customer.DoesNotExist:
        info = Customer.objects.create(
            name=name,
            mobile=mobile,
            id_card=id_card,
            gender=gender,
            rant=4
        )
        info.save()

def reservation(request):
    res = {}
    msg = ''
    if request.method == 'POST':
        name = request.POST.get('name')
        id_card = request.POST.get('id_card')
        people_num = request.POST.get('people')
        mobile = request.POST.get('mobile')
        s_time = request.POST.get('startDate')
        e_time = request.POST.get('endDate')
        gender = request.POST.get('gender')
        room_type = request.POST.get('room_type')
        save_customer(name, mobile, id_card, gender)
        money = request.POST.get('money')
        money = re.findall('\d+', money)[0]
        room = Room.objects.filter(type=int(room_type), status=1)[:1]
        room_num = room[0].num
        Room.objects.filter(num=room_num).update(status=2,is_book=1,time=s_time)
        order = HotelOrder.objects.create(
            name = name,
            id_card = id_card,
            people_num = people_num,
            mobile = mobile,
            s_time = datetime.datetime.strptime(s_time+' 12', '%Y-%m-%d %H'),
            e_time = datetime.datetime.strptime(e_time+' 12', '%Y-%m-%d %H'),
            type = 2,
            gender = gender,
            room_type =room_type,
            room_num = room_num,
            money=money,
        )
        order.save()
        msg = name + '的信息办理成功！房间号：' + room_num
    search_room(res)
    res['active'] = 'reservation'
    res['display'] = 1
    res['msg'] = msg
    return render(request, 'reservation.html', res)

def search_room(res):
    rooms = Room.objects.filter(status=1)
    count = rooms.count()
    standard_room = 0
    big_room = 0
    business_double_room = 0
    deluxe_big_room = 0
    for room in rooms:
        if room.type == 1:
            standard_room += 1
        if room.type == 2:
            big_room += 1
        if room.type == 3:
            business_double_room += 1
        if room.type == 4:
            deluxe_big_room += 1
    res['standard_room'] = standard_room
    res['big_room'] = big_room
    res['business_double_room'] = business_double_room
    res['deluxe_big_room'] = deluxe_big_room

def check_out(request):
    res = {}
    msg = ''
    s_msg = ''
    if request.method == 'POST':
        name = request.POST.get('name')
        r = HotelOrder.objects.filter(name=name, type__in=[1,2], e_time__gte=datetime.date.today())
        if not r:
            msg = '未查询到相关用户的住房信息'
        else:
            item = {}
            item['name'] = r[0].name
            item['room_num'] = r[0].room_num
            item['people_num'] = r[0].people_num
            item['s_time'] = r[0].s_time
            item['e_time'] = r[0].e_time
            r1 = Room.objects.get(num=r[0].room_num)
            item['room_status'] = RoomStatus.get(r1.status)
            item['room_type'] = RoomType.objects.get(type_num=r[0].room_type).name
            res['data'] = item
        check_out = request.POST.get('check_out')
        if check_out and check_out == '1':
            room_num = request.POST.get('room_num')
            HotelOrder.objects.filter(name=name, room_num=int(room_num), e_time__gte=datetime.date.today()).update(type=3)
            Room.objects.filter(num=int(room_num)).update(status=1)
            s_msg = '退房手续办理成功'
    res['msg'] = msg
    res['s_msg'] = s_msg
    res['active'] = 'check_out'
    res['display'] = 1
    return render(request, 'check_out.html', res)

def vacancy(request):
    res = {}
    # r = HotelOrder.objects.filter(e_time__lte=datetime.date.today())
    # room_nums = [i.room_num for i in r]
    # raise NameError
    # HotelOrder.objects.filter(e_time__lte=datetime.date.today()).update(type=3)
    # Room.objects.filter(num__in=room_nums).update(status=1)
    room_type = request.GET.get('room_type')
    if room_type:
        rooms = Room.objects.filter(status=1, type=room_type).order_by('num')
    else:
        rooms = Room.objects.filter(status=1).order_by('num')
    res['rooms'] = rooms
    res['active'] = 'vacancy'
    res['display'] = 1
    return render(request, 'vacancy.html', res)

def reservation_info(request):
    res = {}
    if request.method == 'POST':
        user_name = request.POST.get('name')
        r = HotelOrder.objects.filter(name=user_name, type=2, e_time__gte=datetime.date.today())
    else:
        room = request.GET.get('room')
        if room:
            HotelOrder.objects.filter(type=2, room_num=room).update(type=1)
            Room.objects.filter(num=room).update(status=5)
        r = HotelOrder.objects.filter(type=2, e_time__gte=datetime.date.today()).order_by('room_num')
    rooms = []
    for i in r:
        item = {}
        item['room_num'] = i.room_num
        item['s_time'] = i.s_time
        item['e_time'] = i.e_time
        r = Room.objects.get(num=i.room_num)
        item['room_status'] = RoomStatus.get(r.status)
        item['room_type'] = RoomType.objects.get(type_num=i.room_type).name
        item['username'] = i.name
        rooms.append(item)
    res['rooms'] = rooms
    res['active'] = 'reservation_info'
    res['display'] = 2
    return render(request, 'reservation_info.html', res)

def cancel_reservation(request):
    room = request.GET.get("room")
    if room:
        HotelOrder.objects.filter(type=2, room_num=room).update(type=3)
        Room.objects.filter(num=room).update(status=1)
    return redirect('/reservation_info')

def enter_info(request):
    res = {}
    room_type = request.GET.get('room_type')
    room_status = request.GET.get('room_status')
    room_num = request.GET.get('room')
    op = request.GET.get('op')
    if room_num:
        if op == 'enter':
            HotelOrder.objects.filter(room_num=room_num, type=2, e_time__gte=datetime.date.today()).update(type=1)
            Room.objects.filter(num=room_num).update(status=5)
        else:
            HotelOrder.objects.filter(room_num=room_num, type=1, e_time__gte=datetime.date.today()).update(type=3)
            Room.objects.filter(num=room_num).update(status=1)
    if room_type:
        hotel_order = HotelOrder.objects.filter(type=room_type, e_time__gte=datetime.date.today()).order_by('room_num')
    elif room_status:
        hotel_order = HotelOrder.objects.filter(status=room_status, e_time__gte=datetime.date.today()).order_by('room_num')
    else:
        hotel_order = HotelOrder.objects.filter(type__in=[1,2], e_time__gte=datetime.date.today()).order_by('room_num')
    order_list = []
    for i in hotel_order:
        item = {}
        item['room_num'] = i.room_num
        item['people_num'] = i.people_num
        item['s_time'] = i.s_time
        item['e_time'] = i.e_time
        r = Room.objects.get(num=i.room_num)
        item['room_status'] = RoomStatus.get(r.status)
        item['room_type'] = RoomType.objects.get(type_num=i.room_type).name
        item['username'] = i.name
        order_list.append(item)
    res['order_list'] = order_list
    res['active'] = 'enter_info'
    res['display'] = 2
    return render(request, 'enter_info.html', res)

def get_order(request):
    page = int(request.GET.get('page', 0))
    res = {}
    user_name = request.POST.get('name')
    if user_name:
        r = HotelOrder.objects.filter(name=user_name)
    else:
        r = HotelOrder.objects.all().order_by('-s_time')[page*20:page*20+20]
    rooms = []
    for i in r:
        item = {}
        item['room_num'] = i.room_num
        item['s_time'] = i.s_time
        item['e_time'] = i.e_time
        r = Room.objects.get(num=i.room_num)
        item['room_status'] = RoomStatus.get(r.status)
        item['room_type'] = RoomType.objects.get(type_num=i.room_type).name
        item['username'] = i.name
        item['money'] = i.money
        rooms.append(item)
    res['rooms'] = rooms
    res['active'] = 'order'
    res['display'] = 2
    res['page_pre'] = page-1 if page>0 else 0
    res['page_next'] = page+1 
    return render(request, 'order.html', res)


def statement(request):
    res = {}
    user_name = request.POST.get('name')
    if user_name:
        r = HotelOrder.objects.filter(name=user_name)
    else:
        r = HotelOrder.objects.all()
    rooms = []
    for i in r:
        item = {}
        item['room_num'] = i.room_num
        item['s_time'] = i.s_time
        item['e_time'] = i.e_time
        r = Room.objects.get(num=i.room_num)
        item['room_status'] = RoomStatus.get(r.status)
        item['room_type'] = RoomType.objects.get(type_num=i.room_type).name
        item['username'] = i.name
        item['money'] = i.money
        rooms.append(item)
    res['rooms'] = rooms
    res['active'] = 'statement'
    res['display'] = 2
    return render(request, 'statement.html', res)

def seven_trend(request):
    today = datetime.date.today()
    r = HotelOrder.objects.filter(s_time__range=(today-datetime.timedelta(days=5), today-datetime.timedelta(days=-1)))
    d = {
        today-datetime.timedelta(days=6):0,
        today-datetime.timedelta(days=5):1,
        today-datetime.timedelta(days=4):2,
        today-datetime.timedelta(days=3):3,
        today-datetime.timedelta(days=2):4,
        today-datetime.timedelta(days=1):5,
        today:6,
    }
    data = [0] * 7
    arr = [[0] * 7, [0] * 7, [0] * 7,[0] * 7]
    for i in r:
        s_time = datetime.datetime.date(i.s_time)
        index = d[s_time]
        data[index] += float(i.money)
        type = int(i.room_type)
        arr[type-1][index] += float(i.money)
    res = {}
    res['status'] = 'ok'
    res['data'] = data
    res['arr'] = arr
    time_list = []
    for j in range(7):
        time_list.append(str(today-datetime.timedelta(days=j)))
    res['time'] = time_list[::-1]
    return JsonResponse(res)

def get_message(request):
    v = conn.llen('msg_list')
    res = {}
    res['status'] = 'ok'
    if v:
        res['msg'] = 1
    else:
        res['msg'] = 0
    return JsonResponse(res)

def message(request):
    v = conn.llen('msg_list')
    room_num = []
    for i in range(v):
        val = conn.lpop('msg_list')
        if val:
            room_num.append(val)
    msg = '，'.join(room_num) 
    # raise NameError
    return render(request, 'msg.html', {'msg':msg})

#指定房间入住
# def decision_making(request):
#     room_num = request.GET.get('room_num')
#     s_time = request.GET.get('s_time')
#     e_time = request.GET.get('e_time')
#     s_time = datetime.datetime.strptime(s_time, '%Y-%m-%d')
#     e_time = datetime.datetime.strptime(e_time, '%Y-%m-%d')
#     type = request.GET.get('type')
#     infos = HotelOrder.objects.filter(
#         room_num=room_num,
#         type=type
#         ).order_by('s_time')[:1]
#     for info in infos:
#         if e_time <= info.s_time:
#             return JsonResponse({'result':False})
#     return JsonResponse({'result': True})

# #预订
# def decision_making1(room_num, s_time, e_time, type):
#     today = datetime.date.today()
#     book_rooms = Room.objects.filter(is_book=1, status=0)
#     sign_rooms = []
#     rooms = []
#     for i in book_rooms:
#         sign_rooms.append(i.num)
#         infos = HotelOrder.objects.filter(type=2, room_type=i).order_by('s_time')
#         tmp = ['today']
#         for j in infos:
#             tmp.extend([j.s_time, j.e_time])
#         if len(tmp) % 2:
#             tmp.append(today)
#         index = 0
#         while index < len(tmp):
#             day = tmp[index+1] - tmp[index]
#             if tmp[index]>= s_time and tmp[index+1] <= e_time:
#                 rooms.append([i.num, day])
#     min = 100000000
#     fangjin = ''
#     for room in rooms:
#         if room[1]< min:
#             min = room[1]
#             fangjian = room[0]
#     if fangjian:
#         return fangjian
#     blank_room = Room.objects.filter(id_book=0)
#     for i in blank_room:
#         try:
#             order = HotelOrder.objects.get(room_num=i.num, type=1)
#             if order.e_time <= s_time and order.room_num not in sign_rooms:
#                 return i.num
#         except:
#             return i.num
#     return